# usage: make fun=function_name
compiler=intel
interface=ilp64
threading=parallel
parallel=intel
omp=iomp5

ifndef $(gnu_path)
   gnu_path=/usr/lib
endif

MKLROOT = /opt/intel/composer_xe_2015.0.090/mkl
EXT=so
_IA=intel64
RES_EXT=so
MKL_PATH = "$(MKLROOT)/lib/$(_IA)"
CMPLR_PATH = "$(MKLROOT)/../lib/$(_IA)"

FOPTS =
LOPTS =

FC=ifort
IFACE_COMP_PART=intel

IFACE_LIB=$(MKL_PATH)/libmkl_$(IFACE_COMP_PART)_ilp64.$(EXT)
FOPTS += $(if $(filter gnu, $(compiler)), -fdefault-integer-8, -i8)

ifeq ($(parallel),gnu)
   IFACE_THREADING_PART=gnu
   GFORTRAN_LIB=-L$(gnu_path) -lgfortran
else
   GFORTRAN_LIB=
   ifeq ($(parallel),pgi)
      IFACE_THREADING_PART=pgi
   else
      IFACE_THREADING_PART=intel
   endif
endif

ifeq ($(_IA),ia32)
   ifeq ($(compiler),intel)
       SPEC_OPT=-mia32
#This option is required by Intel(R) 11.0 compiler to produce workable binaries for Pentium(R) III.
#If you don't need it, you can remove this option.
   endif
   IFACE_LIB=$(MKL_PATH)/libmkl_$(IFACE_COMP_PART).$(EXT)
endif

ifeq ($(threading),sequential)
   THREADING_LIB=$(MKL_PATH)/libmkl_sequential.$(EXT)
   OMP_LIB =
   GFORTRAN_LIB=
else
   THREADING_LIB=$(MKL_PATH)/libmkl_$(IFACE_THREADING_PART)_thread.$(EXT)
   ifeq ($(parallel),pgi)
      FOPTS += -mp
   endif
   ifeq ($(omp),gomp)
      OMP_LIB = -L$(gnu_path) -l$(omp)
   else
      ifeq ($(omp),pgmp)
        OMP_LIB =
      else
        OMP_LIB = -L$(CMPLR_PATH) -l$(omp)
      endif
   endif
endif

CORE_LIB=$(MKL_PATH)/libmkl_core.$(EXT)

MKL_LIBS=$(LOPTS) $(IFACE_LIB) -Wl,--start-group $(THREADING_LIB) $(CORE_LIB) -Wl,--end-group $(OMP_LIB)


ifndef F95ROOT
   F95ROOT = $(MKLROOT)
   ifneq ($(compiler),intel)
     $(error F95ROOT is mandatory parameter for $(compiler))
   endif
endif

ifeq ($(_IA),ia32)
   MODPATH=$(F95ROOT)/include/$(_IA)
   LIB95=$(F95ROOT)/lib/$(_IA)/libmkl_blas95.a
else
   MODPATH=$(F95ROOT)/include/$(_IA)/$(interface)
   LIB95=$(F95ROOT)/lib/$(_IA)/libmkl_blas95_$(interface).a
endif

RES = $(addsuffix .res ,$(fun))

# app:
# 	$(MAKE) $(RES)

$(fun): %: %.f90
	$(FC) $(SPEC_OPT) $(FOPTS) -I $(MODPATH) -I $(MKLROOT)/include -w \
	$^ common_functions.f90 FEM.f90 MySparseOperator.f90 \
	$(LIB95) $(MKL_LIBS) -lpthread -ldl $(GFORTRAN_LIB) -o $*.app
	./$*.app



clean:
	$(RM) *.app
